package storeMovie.Util;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import storeMovie.JavaBean.Order;

public class OrderManager {
	//private Session session=null;
	public OrderManager(){
		//session= SessionFactoryUtil.getSessionFactory().getCurrentSession();
		//session.beginTransaction();
	}
	
	public void saveOrder(Order order) {
		Session session=null;
		Transaction t = null;
		try{
			session = HibernateUtil.currentSession();
			t = session.beginTransaction();
			session.save(order);
			//session.getTransaction().commit();
			t.commit();
		}catch (Exception e) {
			//System.out.println("inser order : " +e.getCause());// TODO: handle exception
			e.printStackTrace();
			t.rollback();
		}
		//session.getTransaction().commit();
	}
	
	public int getMaxOrderId(String userName) {
		Session session=null;
		try{
			session = HibernateUtil.currentSession();
			Query query = session.createQuery("select Max(ordeId)AS OrdId from Order order where order.userName=?");
			query.setParameter(0, userName);
			List list= query.list();
			int id;
			if(list==null){
				return -1;
			}else{
				id=(Integer)list.get(0);
				return id;
			}
		}catch (Exception e) {
			System.out.println(e.getCause());// TODO: handle exception
			return -1;
		}
	}
	public List<Order> getOrderByUserName(String userName) {
		Session session=null;
		List<Order> listOrders =null;
		try{
			session=HibernateUtil.currentSession();
			Query query = session.createQuery("from Order where userName=?");
			query.setParameter(0, userName);
			listOrders=query.list();
			return listOrders;
		}catch (Exception ex) {
			ex.printStackTrace();
		}
		return listOrders;
	}
}
